// IPC请求日志装饰器
interface IPCLogConfig {
  logRequest?: boolean;
  logResponse?: boolean;
  logError?: boolean;
  maxLogLength?: number;
}

const defaultConfig: IPCLogConfig = {
  logRequest: true,
  logResponse: true,
  logError: true,
  maxLogLength: 1000
};

// 格式化数据用于日志输出
function formatData(data: any, maxLength: number = 1000): string {
  try {
    const jsonStr = JSON.stringify(data, null, 2);
    if (jsonStr.length > maxLength) {
      return jsonStr.substring(0, maxLength) + '... (truncated)';
    }
    return jsonStr;
  } catch (error) {
    return String(data);
  }
}

// 生成唯一的请求ID
function generateRequestId(): string {
  return Math.random().toString(36).substring(2, 9);
}

// IPC请求装饰器
export function ipcLogger(config: IPCLogConfig = {}) {
  const finalConfig = { ...defaultConfig, ...config };
  
  return function (
    _target: any,
    propertyKey: string | symbol,
    descriptor: PropertyDescriptor
  ) {
    const originalMethod = descriptor.value;
    
    descriptor.value = async function (...args: any[]) {
      const requestId = generateRequestId();
      const methodName = String(propertyKey);
      const startTime = performance.now();
      
      // 日志请求
      if (finalConfig.logRequest) {
        console.group(`🔵 IPC Request [${requestId}] ${methodName}`);
        console.log('📤 Method:', methodName);
        console.log('⏰ Time:', new Date().toLocaleTimeString());
        if (args.length > 0) {
          console.log('📦 Parameters:', formatData(args, finalConfig.maxLogLength));
        }
        console.groupEnd();
      }
      
      try {
        const result = await originalMethod.apply(this, args);
        const duration = Math.round(performance.now() - startTime);
        
        // 日志响应
        if (finalConfig.logResponse) {
          console.group(`🟢 IPC Response [${requestId}] ${methodName}`);
          console.log('✅ Status: Success');
          console.log('⏱️ Duration:', `${duration}ms`);
          console.log('📥 Response:', formatData(result, finalConfig.maxLogLength));
          console.groupEnd();
        }
        
        return result;
      } catch (error) {
        const duration = Math.round(performance.now() - startTime);
        
        // 日志错误
        if (finalConfig.logError) {
          console.group(`🔴 IPC Error [${requestId}] ${methodName}`);
          console.log('❌ Status: Error');
          console.log('⏱️ Duration:', `${duration}ms`);
          console.error('💥 Error:', error);
          console.groupEnd();
        }
        
        throw error;
      }
    };
    
    return descriptor;
  };
}

// 简化的装饰器，只记录基本信息
export function ipcLoggerSimple() {
  return ipcLogger({
    logRequest: true,
    logResponse: true,
    logError: true,
    maxLogLength: 500
  });
}

// 详细的装饰器，记录完整信息
export function ipcLoggerDetailed() {
  return ipcLogger({
    logRequest: true,
    logResponse: true,
    logError: true,
    maxLogLength: 5000
  });
}

// 静默的装饰器，只记录错误
export function ipcLoggerSilent() {
  return ipcLogger({
    logRequest: false,
    logResponse: false,
    logError: true,
    maxLogLength: 1000
  });
}
